<?php
namespace control;
// 固定资产登记
class assetUseClass extends adIndexClass
{
    private const page = 'assetUse';         # 权限
    private const table = 'asset_use';        # 数据表
    private const tableMx = 'asset_use_detail'; # 子表
    private const title = '固定资产领用';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "领用单号",
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'receiver'  => [
                        'name'  => '领用人',
                        'width' => 250,
                    ],
                    'department'         => [
                        'name'  => '领用人部门',
                        'width' => 250,
                    ],
                    'stid'          => [
                        'name'  => '制单人',
                        'width' => 250,
                    ],
                    'receivingDate'          => [
                        'name'  => '领用日期',
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "领用单号" => text(array("name" => "orderNo")),
                    "领用人"   => text(array("name" => "receiver")),
                    '领用人部门' => selectMultiple([
                        "name" => "department",
                        'table' => 'department',
                        'sqlId' => 'id',
                        'sqlField' => 'name',
                    ]),
                ],
                [
                    "制单人" => selectMultiple([
                        "name" => "stid",
                        'table' => 'staff',
                        'where' => "state !='离职'",
                        'sqlId' => 'stid',
                        'sqlField' => 'name',
                    ]),
                    "领用日期" => text(
                        [
                            'name' => 'receivingDate',
                            'laydate' => ['range' => '~', 'type' => 'date'],
                        ]
                    ),
                    "状态" => select(["name" => "state", 'option' => ['制单', '审核中', '已通过']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*固定资产入口页*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $root = $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&acid=' . $this->post('objId');
            $button .= "
			<span class='spanButton' onclick=\"newIframe('新建固定资产','" . $root . "')\">新建</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*固定资产列表*/
    public function homeSearch(): bool|string
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'coid' => self::$coid,
        ];
        $like = [
            'orderNo' => $this->post('orderNo'),
            'department' => $this->post('department'),
            'stid' => $this->post('stid'),
            'state' => $this->post('state'),
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);
        if ($this->post('receivingDate')) {
            $where .= self::timeComparison($this->post('receivingDate'), 'date', 'receivingDate');
        }
        if ($this->post('receiver')) {
            $where .= " AND stid in (SELECT stid FROM staff WHERE name LIKE '%{$this->post('receiver')}%') ";
        }
        $where .= $this->seeSelf(self::page);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'receivingDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => ["name" => "listId", "value" => $array['id']],
                "detail" => [
                    "title" => "固定资产详情",
                    "click" => "newIframe('固定资产详情','" . root . "control/adIndex.html?cla=" . $this->get(
                            'cla'
                        ) . "&fun=detail&id=" . $array['id'] . "')",
                ],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'receiver':
                    case 'stid':
                        $row[] = self::findStaff($array[$key]);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function editPage(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $where = $this->seeSelf(self::page, 'stid');
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "fun" => "subForm('" . self::page . "EditPageForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editPageEdit')",
            'style' => 'li-btn-blue-bg',
        ];

        $tr[] = ['', '固定资产编码', '名称', '品牌', '规格型号', '存放地点', '领用数量', '领用存放地点', '备注'];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {
            $asset = query('asset', " id = '$array[atid]'");
            $asset_reg = query('asset_reg',"id = '$asset[regId]'");
            $attribute='';
            if ($asset_reg['cardMethod'] =='按数量拆分建卡'){
                $attribute = "readonly";
            }
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'atid[]', 'value' => $array['atid'])),
                $asset['orderNo'],
                $asset['name'],
                $asset['brand'],
                $asset['model'],
                $asset['storage'],
                text(array('name' => 'num[]','other'=>$attribute." onblur=\"calculateTotal()\" ", 'type' => 'number', 'value' => $array['num'])),
                text(array('name' => 'storage[]', 'class' => 'text', 'value' => $array['storage'])),
                text(array('name' => 'mxText[]', 'class' => 'text', 'value' => $array['text'])),
            ];
        }
        $total      = [
            6  => "<span id='total_num'>" . self::lostZero(array_sum(array_column((array)$result['array'],'num')),'num') . "</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $but = <<<efo
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name=assetUseEditPageForm]').serialize())">选择固定资产</span>
                 <input id="barcode" style="margin-left: 20px" type="text" placeholder="输入或扫码"/>
                 <label class="checkbox"><input id="cancel_button" type="checkbox" ><span></span>&nbsp;撤销</label>
efo;
        $staffArr = componentClass::departmentToStaff($this->controlJob['departmentId']);
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must.'领用部门'=>selectMultiple([
                        "name" => "departmentId",
                        "title" => "领用部门",
                        'value' => $info['departmentId'] ?: $this->controlJob['departmentId'],
                        'table' => 'department',
                        'where'=>" 1=1 order by time,list asc",
                        'sqlId' => 'id',
                        'sqlField' => 'name',
                        'change'=>'getStaff'
                    ]),
                    '领用人' => "<div id='pickId' class='full'>".selectMultiple([
                            "name" => "receiver",
                            "title" => "请选择",
                            'value' => $info['receiver'] ?: self::$stid,
                            'table' => 'staff',
                            'where' => "state !='离职' and stid In ('".implode("','",$staffArr)."')" . $where,
                            'sqlId' => 'stid',
                            'sqlField' => 'name'
                        ])."</div>",
                    must . '领用日期' => text(
                        [
                            'name' => "receivingDate",
                            'class' => 'text',
                            'value' => $info['receivingDate'] ?: $this->date,
                            'laydate' => [],
                        ]
                    ),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]) . hidden(
                            ['name' => 'id', 'value' => $info['id'] ?: $id]
                        ),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '领用明细',
            'button' => $but,
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
        ]);
        //返回
        $data['html'] .= $this->js();
        return $this->tab($data);
    }

    public function getStaff(): bool|string
    {
        $departmentId = $this->post('departmentId');
        $where = $this->seeSelf(self::page);
        $staffArr = componentClass::departmentToStaff($departmentId);
        $json['html'] = selectMultiple([
            "name" => "receiver",
            "title" => "请选择",
            'table' => 'staff',
            'where' => "state !='离职' and stid In ('".implode("','",$staffArr)."')" . $where,
            'sqlId' => 'stid',
            'sqlField' => 'name'
        ]);
        return json_encode($json,320);
    }
    /**
     * JS
     * @return string
     */
    public function js(): string
    {
        $cla = self::page;
        return <<<eof
<script>
function getStaff(e){
      $.post(root+'control/adIndex.html?cla={$cla}&fun=getStaff',{departmentId:e.value},function(res) {
          $("#pickId").html(res.html);
      },'json');
}
/***扫码操作***/
$("#barcode").on('keydown',function(event) {
    if (event.keyCode===13){
        let code = $(this).val();//条码
        if (!code){
            msg('未找到条码','error')
            return '';
        }
        //判断是否是撤销操作
        if ($("#cancel_button").is(":checked")){
            //撤销
            $.post(root+'control/adIndex.html?cla={$cla}&fun=getMaterial',{code:code},function(res) {
                  if (res.warn===2){
                      $("#materialTable").find("input[name='atid[]']").each(function() {
                           if (res.data === $(this).val()){
                               $(this).parent().parent().remove();
                           }
                      });
                  }else{
                      msg(res.warn,'error');
                  }
            },'json')
        }else{
            //添加
             $.post(root+'control/adIndex.html?cla={$cla}&fun=getMaterial',{code:code},function(res) {
                 if (res.warn===2){
                       $.post(root+'control/adIndex.html?cla={$cla}&fun=addMxEdit',{materialId:res.data,classify:'barcode'},function(res) {
                           if (res.warn ==2){
                               $("#materialTable tbody").append(res.html);
                           }else{
                               msg(res.warn,'error');
                           }
                           
                       },'json')
                  }else{
                      msg(res.warn,'error');
                  }
             },'json')
        }
    }
});



function addRow(){
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
             if (res.warn ==2){
                $('#assetUseAddMx').hide()
                $("#materialTable tbody").append(res.html);
                resetNumber($("#materialTable"))
                calculateTotal()
           }else{
               msg(res.warn,'error');
           }
            
        },'json');
}
//合计
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let num = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
}
</script>
eof;

    }


    /*基本资料新增或修改-异步处理*/
    public function editPageEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $atidArr = $this->post('atid');
        $storageArr = $this->post('storage');
        $numArr = $this->post('num');
        $mxTextArr = $this->post('mxText');

        $field = [
            'departmentId'=>$this->post('departmentId'),
            'receiver' => $this->post('receiver'),
            'receivingDate' => $this->post('receivingDate'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'receiver' => '领用人',
            'receivingDate' => '领用日期',
        ];
        $rules = [
            'receiver' => 'required',
            'receivingDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择领用明细';
        } elseif (static::is_null_array($atidArr)) {
            $json['warn'] = '请选择领用明细';
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = '数量请填写完整';
        } elseif (!empty($info['id']) && $info['state'] != '制单') {
            $json['warn'] = '此单据不是制单状态，不能编辑';
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            // 职位名称
            $field['department'] = departmentClass::getTypeName($field['departmentId']);
            $this->startTrans();
            if (!$info['id']) {
                $orderNo = codeTemplateClass::generateCode(self::page, [
                    'table' => self::table,
                    'prefix' => 'ZCSL' . date('Ymd'),
                    'default' => '001',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'orderNo' => $orderNo,
                    'state' => '制单',
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }

            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::tableMx, "id = '$nid'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableMx,
                        "field" => [
                            'atid' => $atidArr[$k],
                            'storage' => $storageArr[$k],
                            'num' => $numArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableMx,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'atid' => $atidArr[$k],
                            'storage' => $storageArr[$k],
                            'num' => $numArr[$k],
                            'text' => $mxTextArr[$k],
                        ],

                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '制单' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => [
                    "act" => 'start',
                    "id" => $info['id'],
                    'body' => self::encryptDecrypt(
                        json_encode([
                            'name' => '闲置资产申领',
                            'table' => self::table,
                            'process' => [
                                // 预览函数
                                'detail' => [
                                    'cla' => $this->get('cla'),
                                    'fun' => 'detail',
                                ],
                                // 保存函数
                                'save' => [
                                    'cla' => $this->get('cla'),
                                    'fun' => 'editPageEdit',
                                ],
                                //执行发起时验证函数
                                'before' => [
                                    'cla' => $this->get('cla'),
                                    'fun' => '',
                                ],
                                //完成发起后执行函数
                                'after' => [
                                    'cla' => $this->get('cla'),
                                    'fun' => '',
                                ],
                            ],
                        ], 320)
                    ),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'addApprover',
                    "id" => $info['id'],
                    'body' => self::encryptDecrypt(
                        json_encode([
                            'table' => self::table,
                        ], 320)
                    ),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'transfer',
                    "id" => $info['id'],
                    'body' => self::encryptDecrypt(
                        json_encode([
                            'table' => self::table,
                        ], 320)
                    ),
                ],
            ];
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => [
                    "act" => 'approval',
                    "id" => $info['id'],
                    'body' => self::encryptDecrypt(
                        json_encode([
                            'table' => self::table,
                            // 当前状态
                            'state' => $info['state'],
                            // 变更
                            'field' => ['state'],   //变更字段 可多个
                            'value' => [
                                'state' => ['制单', '已通过'],
                            ],
                            // 审核时回调
                            'process' => [
                                //执行首次审核时验证
                                'before' => [
                                    'cla' => $this->get('cla'),
                                    'fun' => '',
                                ],
                                //执行末次审核后处理
                                'after' => [
                                    'cla' => $this->get('cla'),
                                    'fun' => 'useDone',
                                    'data' => ['id' => $info['id']],
                                ],
                            ],
                        ], 320)
                    ),
                ],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] == '审核中') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'cancel',
                    "id" => $info['id'],
                    'body' => self::encryptDecrypt(
                        json_encode([
                            'table' => self::table,
                            // 当前状态
                            'state' => $info['state'],
                            // 变更
                            'field' => ['state'],   //变更字段 可多个
                            'value' => [
                                'state' => ['制单'],
                            ],
                            'process' => [
                                //完成发起后执行函数
                                'after' => [
                                    'cla' => $this->get('cla'),
                                    'fun' => '',
                                ],
                            ],
                        ], 320)
                    ),
                ],
            ];
        }
        return $button;
    }


    /**
     * 领用
     *
     * @param array $data
     * @return void
     */
    public function useDone(array $data)
    {
        $id = $data['id'];
        $info = query(self::table, " id = '$id' ");
        $result = find([
            'table' => self::tableMx,
            'where' => " orderId = '{$info['id']}' AND  state = '待归还' ",
        ]);
        foreach ((array)$result['array'] as $value) {
            static::update([
                'table' => 'asset',
                'field' => [
                    'user' => $info['receiver'],
                    'userDepartment' => $info['department'],
                    'storage' => $value['storage'],
                    'state' => '使用中',
                    'unused'=>'否',
                    'departmentId'=>$info['departmentId']
                ],
                'where' => " id = '{$value['atid']}' ",
            ]);
            static::insert([
                'table' => 'asset_revert',
                'field' => [
                    'id' => self::getNo(),
                    'coid' => self::$coid,
                    'atid' => $value['atid'],
                    'userDepartment' => $info['department'],
                    'user' => $info['receiver'],
                    'type' => '领用',
                    'storage' => $value['storage'],
                ],
            ]);
        }
    }

    public function detail(): string
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $html = "你没有查看权限";
        } elseif (!$this->get('id')) {
            $html = "ID为空";
        } elseif (!$info['id']) {
            $html = "未找到此信息";
        } else {
            $data = [
                "id" => $info['id'],
            ];
            //按钮
            $button = [];
            //审核按钮
            $button = array_merge($button, $this->auditButton($info));
            if ($info['state'] == '制单') {

                if ($this->power(self::page, "edit")) {
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => self::title,
                        "url" => $this->root . 'control/adIndex.html?cla=' . $this->get(
                                'cla'
                            ) . '&fun=editPage&id=' . $info['id'],

                    ];
                }
                if ($this->power(self::page, "del")) {
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }

            // 子表
            $mxtr[] = ['卡片编码', '名称', '品牌', '规格型号', '存放地点', '领用数量', '领用存放地点', '备注'];
            //订单明细
            $all = self::sqlFind("SELECT * FROM " . self::tableMx . " WHERE orderId = '$info[id]' ORDER BY time ");
            foreach ($all as $array) {
                $asset = query('asset', " id = '{$array['atid']}' ");
                $mxtr[] = [
                    $asset['orderNo'],
                    $asset['name'],
                    $asset['brand'],
                    $asset['model'],
                    $asset['storage'],
                    $array['num'],
                    $array['storage'],
                    $array['text'],
                ];
            }
            $total_tr = [
                5  => self::lostZero(array_sum(array_column((array)$all,'num')),'num'),
            ];

            // 生成子表单页面
            $detailHtml = $this->listTable(array('tr' => $mxtr, 'showSort' => true, 'total' => $total_tr));
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                [
                    [
                        "领用人部门" => $info['department'],
                        "领用人" => self::findStaff($info['receiver']),
                        "领用日期" => $info['receivingDate'],
                        "领用单号" => $info['orderNo'],
                    ],
                    [
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state'],
                    ],
                    [
                        '备注'=>pre($info['text'])
                    ],
                ],
            ]);
            $data['html'] .= $this->detailList([
                'title' => '明细',
                'html' => $detailHtml,
            ]);
            $data['html'] .= $this->detailBlock([
                '流程' => auditClass::auditRecord(self::table, $info['id'])
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 添加固定资产
     *
     * @return bool|string
     */
    public function addMx(): bool|string
    {
        $html =
            text(["name" => "acid", "title" => "分类"])
            . text(["name" => "orderNo", "title" => "编码"])
            . text(["name" => "name", "title" => "名称"])
            . text(["name" => "model", "title" => "规格"])
            . hidden(array('name' => 'atid', 'value' => $this->post('atid') ? implode(',', $this->post('atid')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(["title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button]);
    }

    /**
     *添加固定资产
     */
    public function addMxSearch(): bool|string
    {
        $materialId = $this->post('atid') ? explode(',', $this->post('atid')) : [];

        $where = (empty($this->post('acid'))) ? ' 1=1 ' : " acid  in (select acid from `asset_catalog` where name LIKE '%{$this->post('acid')}%') ";
        $and = " and unused='是' and isCut = 0 and id not in ('" . implode("','", $materialId) . "')";
        $like = [
            'name' => $this->post('name'),
            'orderNo' => $this->post('orderNo'),
            'model' => $this->post('model'),
        ];
        $equal = [
            'coid' => self::$coid,
        ];

        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "asset",
            "where" => $where,
            'pageNum' => 50,
            "order" => " `time` ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll, '分类', '固定资产编码', '名称', '品牌', '规格'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            $tr[] = [
                $this->dominate($dominate),
                assetCatalogClass::getCatalogName($array['acid']),
                $array['orderNo'],
                $array['name'],
                $array['brand'],
                $array['model'],
            ];
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * 添加
     *
     * @return bool|string
     */
    public function addMxEdit(): bool|string
    {
        $mxIdArr = $this->post('mxId');
        $materialId = $this->post('materialId');
        $classify = $this->post('classify');//扫码添加类型
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif ($classify !== 'barcode' && (empty($mxIdArr) || !is_array($mxIdArr))) {
            $json['warn'] = '请选择固定资产';
        } elseif ($classify === 'barcode' && empty($materialId)) {
            $json['warn'] = '请选择固定资产';
        } else {
            $json['html'] = '';
            if ($classify === 'barcode') {
                $mxIdArr[] = $materialId;
            }
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $asset = query('asset', " id = '$mxId'");
                $asset_reg = query('asset_reg',"id = '$asset[regId]'");
                $attribute='';
                if ($asset_reg['cardMethod'] =='按数量拆分建卡'){
                    $attribute = "readonly";
                }

                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => suiji())) .
                    hidden(array('name' => 'atid[]', 'value' => $mxId)),
                    $asset['orderNo'],
                    $asset['name'],
                    $asset['brand'],
                    $asset['model'],
                    $asset['storage'],
                    text(array('name' => 'num[]','other'=>$attribute." onblur=\"calculateTotal()\" ", 'type' => 'number', 'value' => 1)),
                    text(array('name' => 'storage[]', 'class' => 'text')),
                    text(array('name' => 'mxText[]', 'class' => 'text')),
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false, 'end' => true));
        }
        return json_encode($json, 320);
    }

    /**
     * 根据条码获取固定资产档案
     */
    public function getMaterial(): bool|string
    {
        if (empty($this->post('code'))) {
            $json['warn'] = "未找到条码";
        } else {
            $asset = query('asset', "orderNo = '" . $this->post('code') . "' and coid = '" . self::$coid . "'");
            $json['data'] = $asset['id'];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): bool|string
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        $append = [];
        switch ($act) {
            case 'delMx':
                $act = 'del';
                $msg = self::title . '删除明细';
                $title = self::page . 'MxDelete';
                $function = 'delMx';
                $form = self::page . 'OperateForm, detailForm';
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'isDelete';
                $form = self::page . 'OperateForm, listForm';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'append' => $append,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    // 确认删除信息
    public function isDelete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey = 'state';
            $fieldVlaue = '制单';

            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if (!static::isNull($info['id'])) {
                    if ($info[$fieldKey] !== $fieldVlaue) {
                        $text .= self::title . "【{$info['id']}】非{$fieldVlaue}状态，无法删除<br>";
                        continue;
                    }
                    // 删除表
                    delete([
                        "table" => self::table,
                        "where" => $where,
                    ]);
                    //添加记录
                    $text .= "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . '<br>';
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "删除了{$x}条" . self::title;
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }

    // 确认删除明细
    public function delMx(): bool|string
    {
        $orderId = $this->post('id');
        $array = $this->post('mxid');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey = 'state';
            $fieldVlaue = '制单';
            $assetUse = query(self::table, " id = '$orderId' ");
            if ($assetUse[$fieldKey] !== $fieldVlaue) {
                $json['warn'] = self::title . "【{$assetUse['id']}】为{$fieldVlaue}状态，无法删除<br>";
            } else {
                foreach ($array as $id) {
                    $where = " id = '$id' AND orderId = '$orderId' ";
                    $info = query(self::tableMx, $where);
                    if ($info['id']) {
                        // 删除表
                        delete(["table" => self::tableMx, "where" => $where]);
                        $x++;
                    }
                }
                $_SESSION['warn'] = "删除了{$x}条明细记录";
                $json['warn'] = 2;
            }
        }

        resp:
        return json_encode($json, 320);
    }
}
